package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.service.ReportService;
import com.sky.vo.TurnoverReportVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //通过传入的时间构造日期列表数据
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        //将传入的日期循环,依次加入集合当中,在遍历的时候注意出口,不要出现OOM问题
        while (!begin.equals(end)) {
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //通过传入的时间参数获取订单基本信息,构造营业额列表数据,查询orders表,状态是已完成,时间是当日
        //遍历dateList集合获取当日时间
        List<BigDecimal> turnoverList=new ArrayList();
        dateList.forEach(date -> {
            //构造map集合存储数据,使得代码更加简洁
            Map map=new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            BigDecimal tur=ordersMapper.sumBy(map);
            tur=tur == null ? BigDecimal.ZERO : tur;
            turnoverList.add(tur);
        });

        //将信息封装成vo传给Controller层
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }
}
